import { useState } from 'react';
import useSWR from 'swr';
import { Select, Descriptions, Spin, Divider } from 'antd';
import { switchesFetcher } from '../services/switches';
import { descFetcher } from '../services/desc';
import Layout from '../components/Layout';

const { Option } = Select;

const useData = () => {
  const [select, setSelect] = useState('1');

  const { data: switchesData } = useSWR('/stats/switches', switchesFetcher);

  const { data: descData } = useSWR(['/stats/desc', select], (_, temp) => descFetcher(temp));

  return {
    isLoading: !descData || !switchesData,
    data: { switchesData, descData },
    select,
    setSelect,
  };
};

export default function Home() {
  const { isLoading, data, select, setSelect } = useData();

  let element = <Spin />;

  if (!isLoading) {
    const { descData } = data;
    const realData = descData[select];

    element = (
      <>
        <Select
          defaultValue={select}
          style={{ width: 120 }}
          onChange={e => {
            setSelect(e);
          }}>
          {data.switchesData.map(item => {
            return (
              <Option key={item} value={item}>
                {item}
              </Option>
            );
          })}
        </Select>
        <Divider />
        <Descriptions title="表" bordered>
          <Descriptions.Item label="DP Desc">{realData['dp_desc']}</Descriptions.Item>
          <Descriptions.Item label="HW Desc">{realData['hw_desc']}</Descriptions.Item>
          <Descriptions.Item label="MFR Desc">{realData['mfr_desc']}</Descriptions.Item>

          <Descriptions.Item label="Serial Num">{realData['serial_num']}</Descriptions.Item>
          <Descriptions.Item label="SW Desc" span={2}>
            {realData['sw_desc']}
          </Descriptions.Item>
        </Descriptions>
      </>
    );
  }

  return <Layout>{element}</Layout>;
}
